<template>
  <pageTabelLayout>
    <template #pageHeader>
  <div class="search-form isheader">
    <div>
      <a-form size="mini" :model="sheetData" layout="inline">
        <a-form-item label="盘点公司" v-if="tabsKeys == 1">
          <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="searchData.companyName" disabled />
        </a-form-item>
        <!-- <CorporateSectorCascader :configCascader="configCascader" @changeCascader="changeCascader" v-if="tabsKeys == 1" /> -->
        <a-form-item label="所属仓库" v-if="tabsKeys == 1">
          <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" placeholder="" v-model="sheetData.warehouseId"
            allow-clear>
            <a-option v-for="(item, index) in warehouseList" :value="item.id" :key="index">
              {{ item.warehouseName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="物料编号" v-if="tabsKeys == 2">
          <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="searchData.materialCode"
            @press-enter="huiche" />
        </a-form-item>
      </a-form>
    </div>
    <div>
      <Toolbar :items="toolbarList" @select="queryHandler" @init="initInventory" @audit="auditInventorySheet"
        @cel="delInventories" @saveData="updateInventoryDetails" @export="exportInventories"
        @add="pageData.showAdd = true" @import="importHandler"></Toolbar>
    </div>
  </div>
  <div class="my-divisders">
    <a-divider orientation="center">
      <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
      <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
    </a-divider>
  </div>
</template>
<template #pageTabel>
    <a-tabs   :lazy-load="true"  :justify="true" :active-key="tabsKeys" @change="tabsChanges">
      <a-tab-pane title="盘点单列表" :key="1">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" :suppressDragLeaveHidesColumns="true" @grid-ready="sheetGridReady"
          style="height: calc(100% - 45px);" @columnResized="onColumnResized" @columnMoved="onColumnMoved"
          @columnVisible="onColumnVisible" :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="sheetList"
          :columnDefs="sheetColDefs" :localeText="localeText1"></AgGridVuesCopys>
        <paginationCopys :page-size-options="pagingList1" :total="sheetData.total" show-total show-jumper show-page-size
          @change="pageChange" style="justify-content: center" :page-size="sheetData.size" :current="sheetData.current"
          @page-size-change="change" />
      </a-tab-pane>
      <a-tab-pane title="盘点明细" :key="2" v-loading="pageData.loadingUp2">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" :suppressDragLeaveHidesColumns="true" @grid-ready="detailGridReady"
          style="height: calc(100% - 45px);" @columnResized="onColumnResized2" @columnMoved="onColumnMoved2"
          @columnVisible="onColumnVisible2" :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="detailList"
          :columnDefs="irnChmOilRubColDefs" :localeText="localeText1"></AgGridVuesCopys>
        <paginationCopys :page-size-options="pagingList1" :total="searchData.total" show-total show-jumper show-page-size
          @change="pageChange1" style="justify-content: center" :page-size="searchData.size" :current="searchData.current"
          @page-size-change="change1" />

        <a-modal v-model:visible="visible" width="auto" @ok="handleOk" @cancel="handleCancel">
          <div><a-image width="200" height="200" :src="qrCodeImg" /></div>
        </a-modal>
      </a-tab-pane>
    </a-tabs>
  </template>
</pageTabelLayout>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { post, get } from '@/api/http'
import { localeText } from '@/api/aggridZw'

import Toolbar from '@/components/Toolbar.vue'
import { Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { ElMessage, ElMessageBox } from 'element-plus'

// import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import { pagingList } from '@/api/paging'
import filedownload from 'js-file-download'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { saveOrUpdateGridState as saveOrUpdateGridState02 } from '@/hooks/useGridState'
const pagingList1: any = ref(pagingList)
const headerShow = ref(true)
const auditStatus = ref(1)
const localeText1: any = ref(localeText)
const sheetList = ref<any>([])
const detailList = ref<any>([])
const inventoryColDefs = ref<any>([])
const visible = ref(false);
const qrCodeImg = ref<any>();

const toolbarList: any = ref(['查询', '审核', '终止盘点', '创建盘点单'])

const pager = reactive({
  total: 10,
  size: 10,
  current: 1,
})

const pageData = reactive({
  showAdd: false,
  showDetails: false,
  isShow: false,
  rHeight: 0,
  loadingUp2: false,
})

const searchData = reactive<any>({
  sheetId: null,
  companyId: null,
  warehouseId: '',
  warehouseType: null,
  total: 10,
  current: 1,
  size: 10,
})

const sheetData = reactive({
  companyId: null,
  companyName: null,
  warehouseId: '',
  warehouseType: null,
  total: 10,
  current: 1,
  size: 10,
})

const firstSheetRow = reactive({
  id: null,
  warehouseType: null,
})

const warehouseList = ref([
  {
    warehouseName: '',
    warehouseTypeId: '',
    id: '',
  },
])

const loadWarehouseList = () => {
  post({
    url: 'wms/warehouse/getWarehouseByPara',
    data: { firmId: searchData.companyId, warehouseTypeId: 2, virtuallyState: 0 },
  }).then(({ code, data }) => {
    if (code === 200) {
      console.log(data)
      warehouseList.value = data
    }
  })
}

onMounted(() => {
  updateGridState01()
  updateGridState02()
  post({
    url: 'wms/inventorySheet/fetchUserInfoByToken',
    data: {},
  }).then(({ code, message, data }) => {
    if (code === 200) {
      searchData.companyId = data.firmId
      searchData.companyName = data.firmName
      sheetData.companyId = data.firmId
      sheetData.companyName = data.firmName
      loadWarehouseList()
      loadSheetList()
    } else {
      Message.error({
        content: message,
        duration: 5000,
      })
    }
  })
})


//导入
const importHandler = () => {
  if (auditStatus.value == 4) {
    Message.warning('此盘点单已审核，无法导入差异对比！')
    return false
  }
  const inputEle: HTMLInputElement = document.createElement('input')
  inputEle.type = 'file'
  inputEle.id = 'fileUploadExcel'
  inputEle.accept =
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
  inputEle.addEventListener('change', async (e) => {
    const formData = new FormData()
    if (detailList.value.length != 0) {
      formData.append('sheetId', detailList.value[0].sheetId)
      formData.append('warehouseId', detailList.value[0].warehouseId)
      formData.append('fixed', 1)
    } else {
      ElMessage.warning('此盘点单没有盘点明细，无法导入差异对比！')
      return
    }

    if (inputEle.files !== null) {
      formData.append('file', inputEle.files[0] || '')
    } else {
      ElMessage.warning('未选择文件！')
      return
    }
    // console.log(formData.values())
    try {
      pageData.loadingUp2 = true
      let res: any = await post({
        url: 'wms/ironInventorySheet/importIronwareInventories',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
          token: sessionStorage.getItem('USER-TOKEN-KEY'),
        },
      })
      if (res.code == 200) {
        ElMessage.success('导入成功')
        pageData.showAdd = false
        loadInventoryList()
        pageData.loadingUp2 = false
        return
      }
      ElMessage.error(res.message)
    } finally {
      pageData.loadingUp2 = false
    }
  })
  inputEle.click()
}
const tabsKeys = ref(1)
const tabsChanges = (e: any) => {
  tabsKeys.value = e
  if (e == 1) {
    toolbarList.value = ['查询', '审核', '终止盘点', '创建盘点单']
    loadSheetList()
  } else if (e == 2) {
    toolbarList.value = ['保存', '导出清单']
    //toolbarList.value = ['导入差异', '导出清单']
    //loadInventoryList()
  }
}

const queryHandler = () => {
  if (tabsKeys.value == 1) {
    sheetData.current = 1
    loadSheetList()
  } else if (tabsKeys.value == 2) {
    loadInventoryList()
  }
}

const initInventory = () => {
  if (sheetData.warehouseId == '') {
    Message.warning('请先选择仓库，再进行盘点初始化')
    return
  }
  console.log(sheetData.warehouseId, 121212)
  let wh: any = warehouseList.value.find((item) => item.id === sheetData.warehouseId)
  post({
    url: 'wms/ironInventorySheet/createInventorySheet',
    data: {
      companyId: sheetData.companyId,
      companyName: sheetData.companyName,
      warehouseId: sheetData.warehouseId,
      warehouseName: wh.warehouseName,
      warehouseType: wh.warehouseTypeId,
      fixed: 1,
    },
  }).then(({ code, message, data }) => {
    if (code === 200) {
      Message.success({
        content: '盘点单创建成功！',
        duration: 5000,
      })
      sheetData.current = 1
      loadSheetList()
    } else {
      Message.error({
        content: message,
        duration: 5000,
      })
    }
  })
}

//盘点单列表
const sheetGridOptions = ref()
const colState = ref()
const sheetGridReady = (params: any) => {
  sheetGridOptions.value = params.api
  colState.value = params.columnApi
}

const loadSheetList = () => {
  post({
    url: 'wms/inventorySheet/findPagedInventorySheets',
    data: {
      companyId: sheetData.companyId,
      warehouseId: sheetData.warehouseId,
      current: sheetData.current,
      size: sheetData.size,
      fixed: 1
    },
  }).then(({ code, data }) => {
    if (code === 200) {
      sheetList.value = data.records
      sheetGridOptions.value.setRowData(data.records)
      sheetData.total = data.total
      if (tabsKeys.value == 1) {
        if (data.records.length > 0) {
          searchData.sheetId = data.records[0].id
          searchData.warehouseType = data.records[0].warehouseType
          auditStatus.value = data.records[0].status
          loadInventoryList()
        } else {
          detailGridOptions.value.setRowData(null)
        }
      }
    }
  })
}

const auditInventorySheet = () => {
  let rows = sheetGridOptions.value.getSelectedRows()
  if (rows.length === 0) {
    Message.warning('请选择需要审核的盘点单！')
    return
  }
  if (rows[0].status != 3) {
    Message.warning('此盘点单盘点未完成或已审核，无法发起审核！')
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认审核此数据?',
    onOk() {
      post({
        url: 'wms/ironInventorySheet/auditInventorySheet',
        data: { id: rows[0].id, fixed: 1 },
      }).then(({ code, data, message }: any) => {
        if (code === 200) {
          Message.success({
            content: '审核成功',
            duration: 5000,
          })
          loadSheetList()
        } else {
          Message.warning(message)
        }
      })
    },
  })
}

//盘点单列表
const detailGridOptions = ref()
const colState2 = ref()
const detailGridReady = (params: any) => {
  detailGridOptions.value = params.api
  colState2.value = params.columnApi
  params.columnApi.setColumnVisible('flowCardCode_1', false)
}

//根据盘点单ID和仓库类型，查询盘点明细
const loadInventoryList = () => {
  post({
    url: 'wms/ironInventorySheet/findPagedInventoryDetails',
    data: searchData,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      detailList.value = data.records
      detailGridOptions.value.setRowData(data.records)
      searchData.total = data.total
    }
  })
}

const exportInventories = () => {
  if (detailList.value.length == 0) {
    ElMessage.warning('当前没有数据')
    return
  }
  post({
    url: '/wms/ironInventorySheet/exportIronwareInventories',
    data: { id: detailList.value[0].sheetId, fixed: 1 },
    responseType: 'blob',
  }).then((res: any) => {
    filedownload(res, '盘点清单.xlsx')
  })
}

//盘点明细--保存
const updateInventoryDetails = () => {
  console.log(auditStatus.value)
  if (auditStatus.value == 4) {
    Message.warning('此盘点单已审核，无法再修改！')
    return
  }
  post({
    url: '/wms/ironInventorySheet/updateCommonInventoryDetails',
    data: detailList.value,
  }).then((res: any) => {
    if (res.code === 200) {
      Message.success({
        content: '保存成功',
        duration: 5000,
      })
      loadSheetList()
      loadInventoryList()
    } else {
      Message.error({
        content: res.message,
        duration: 5000,
      })
    }
  })
}

const pageChange = (val: any) => {
  sheetData.current = val
  loadSheetList()
}

const pageChange1 = (val: any) => {
  searchData.current = val
  loadInventoryList()
}

function change(val: any) {
  sheetData.size = val
  loadSheetList()
}

function change1(val: any) {
  searchData.size = val
  loadInventoryList()
}


const handleOk = () => {
  visible.value = false;
};

const handleCancel = () => {
  visible.value = false;
}


const createQrCode = (code: any) => {
  if (code == null || code == '') {
    Message.warning('此数据无设备编码，无法生成二维码！')
    return
  }
  post({
    url: 'wms/ironInventorySheet/createQrCode',
    data: { equipmentCode: code },
    responseType: 'blob'
  }).then((res) => {
    console.log(res);
    const reader = new FileReader();
    reader.readAsDataURL(res);
    reader.onload = function () {
      qrCodeImg.value = reader.result;
      visible.value = true;
    };
  })
}

const delInventories = () => {
  let rows = sheetGridOptions.value.getSelectedRows()
  if (rows.length === 0) {
    Message.warning('请选择要终止的盘点单！')
    return
  }
  if (rows[0].status == 4) {
    Message.warning('此数据已经审核完成，无法终止！')
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '是否终止此盘点并解锁此仓库?',
    onOk() {
      post({
        url: 'wms/ironInventorySheet/discardInventorySheet',
        data: rows[0],
      }).then(({ data, code, message }: any) => {
        if (code === 200) {
          Message.success({
            content: '解锁成功',
            duration: 5000,
          })
          loadSheetList()
        } else {
          Message.error({
            content: message,
            duration: 5000,
          })
        }


      })
    },
  })
}

const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}

const sheetColDefs = [
  {
    showRowGroup: 'hide_def',
    checkboxSelection: true,
    pinned: 'left',
    width: 200,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  { headerName: '盘点单号', field: 'code', width: 224 },
  { headerName: '公司', field: 'companyName', width: 224 },
  { headerName: '仓库名称', field: 'warehouseName', width: 224 },
  {
    headerName: '仓库类型',
    field: 'warehouseType',
    valueGetter: (params: any) => {
      switch (params.data.warehouseType) {
        case 2:
        case 7:
          return '五金仓'
      }
        },
    width: 224,
  },
  { headerName: '创建人', field: 'createUser', width: 224 },
  { headerName: '创建日期', field: 'createTime', width: 224 },
  {
    headerName: '状态',
    field: 'status',
    valueGetter: (params: any) => {
      switch (params.data.status) {
        case 1:
          return '未开始'
        case 2:
          return '进行中'
        case 3:
          return '已完成'
        case 4:
          return '已审核'
      }
    },
    width: 224,
  },
  {
    headerName: '操作',
    field: 'id',
    filter:false,
    cellRenderer: {
      template: `
                       <a-button @click="switchInventoryList">盘点</a-button>
                   `,
      methods: {
        switchInventoryList() {
          searchData.current = 1
          searchData.sheetId = this.params.value
          searchData.warehouseType = this.params.data.warehouseType
          auditStatus.value = this.params.data.status
          loadInventoryList()
          tabsChanges(2)
        },
      },
    },
    width: 224,
    pinned: 'right'
  },
]

const irnChmOilRubColDefs = [
  {
    showRowGroup: 'hide_def',
    checkboxSelection: true,
    pinned: 'left',
    width: 50,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  { headerName: '物料大类', field: 'majorCategory', width: 150 },
  { headerName: '物料中类', field: 'middleCategory', width: 150 },
  { headerName: '物料小类', field: 'subCategory', width: 150 },
  { headerName: '物料编号', field: 'materialCode', width: 150 },
  { headerName: '物料名称', field: 'materialName', width: 150 },
  { headerName: '设备编码', field: 'equipmentCode', width: 150 },
  { headerName: '所属区域', field: 'district', width: 150 },
  { headerName: '位置号', field: 'locationCode', width: 150 },
  { headerName: '规格', field: 'specification', width: 150 },
  { headerName: '数量', field: 'initCount', width: 150 },
  {
    headerName: '实际数量',
    field: 'realCount',
    editable: true,
    cellRenderer: (params: any) => {
      return "<span style = 'padding:20px;background:#00ffff'>" + (params.value) + '</span>'
    },
    cellEditor: 'agTextCellEditor',
    onCellValueChanged: (params: any) => {
      const newValue = params.newValue;
      var numberRegex = /^(\-|\+)?\d+$/;

      if (!numberRegex.test(newValue)) {
        params.node.setDataValue(params.column.colId, params.oldValue);
      }
      nextTick(() => {
        params.api.refreshCells({ rowNodes: [params.node], columns: [params.column] });
      })
    },
    valueFormatter: (params: any) => {
      if (typeof params.value === 'number') {
        return (params.value);  // 转为两位小数
      }
      return params.value;
    },
    valueSetter: (params: any) => {
      if (params.newValue != null) {
        params.data[params.colDef.field] = params.newValue;
        return true; // 返回 true，表示值已更新
      }
      return false; // 返回 false，表示值未更新
    },
    width: 150,
  },
  {
    headerName: '差异数量',
    field: 'diffCount',
    valueGetter: (params: any) => {
      params.data.diffCount = params.data.realCount - params.data.initCount
      return (params.data.diffCount).toFixed(2)
    },
    width: 150,
  },
  { headerName: '单位', field: 'unit', width: 150 },
  {
    headerName: '操作',
    field: 'id',
    cellRenderer: {
      template: `<a-button @click="createCodeImg">二维码</a-button>`,
      methods: {
        createCodeImg() {
          createQrCode(this.params.data.equipmentCode);
        },
      },
    },
    width: 150,
    pinned: 'right'
  },
]

const configCascader = ref<{}>({
  corporateWidth: '10rem', //公司宽度
  sectorWidth: '180px', //部门宽度
  corporateRquired: false, //公司是否必填
  sectorRquired: false, //部门是否必填
  size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '选择公司', //公司label
  sectorName: '选择部门', //部门label
  cascaderShow: 'sector', //配置部门不显示
})
const changeCascader = (data: any) => {
  const { corporateId, sectorId, sectorLabel, corporateLabel } = data
  searchData.companyId = corporateId
}
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('HardwareInventoryOfFixedAssets-1', sheetGridOptions, colState, sheetColDefs)
const onColumnMoved = () => {
  saveGridState01()
}
const onColumnResized = () => {
  saveGridState01()
}
const onColumnVisible = () => {
  saveGridState01()
}
const { saveGridState: saveGridState02, updateGridState: updateGridState02 } = saveOrUpdateGridState02('HardwareInventoryOfFixedAssets-2', detailGridOptions, colState2, irnChmOilRubColDefs)
const onColumnMoved2 = () => {
  saveGridState02()
}
const onColumnResized2 = () => {
  saveGridState02()
}
const onColumnVisible2 = () => {
  saveGridState02()
}
</script>
<script lang="ts">
export default {
  name: 'ProductInStock',
}
</script>

<style scoped>
.arco-select-dropdown {
  width: 150px;
}
</style>



